package com.xsmart.oa.services.mall.mymenu;

import com.xsmart.common.constant.Constant;
import com.xsmart.common.constant.ResultConstant;
import com.xsmart.common.entity.RequestBean;
import com.xsmart.common.entity.ResponseBean;
import com.xsmart.common.services.LoginTokenService;
import com.xsmart.oa.dao.mall.mymenu.RegisterDao;
import com.xsmart.common.entity.user.InfsUsers;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RegisterService {

    public static final Logger logger = LoggerFactory.getLogger(RegisterService.class);

    @Autowired
    RegisterDao registerDao;
    @Autowired
    LoginTokenService loginTokenService;

    public ResponseBean register(RequestBean requestBean) {
        ResponseBean responseBean = requestBean.getResponseBean();
        InfsUsers user = new InfsUsers();
        String userName = requestBean.getRequestParamString("userName");

        //根据用户名判断是否已经存在用户
        Map<String, Object> users = registerDao.findByUsername(userName);
        if (users != null) {
            responseBean.setResult(ResultConstant.USER_EXIST);
        } else {
            String password = requestBean.getRequestParamString("password");
            List<String> questions = (List<String>) requestBean.getRequestParam("question");
            if (questions != null && questions.size() > 0) {
                String question = questions.get(0);
                user.setQuestion(question);
            }
            String answer = requestBean.getRequestParamString("answer");
            List<Integer> sexs = (List<Integer>) requestBean.getRequestParam("sex");

            if (sexs != null && sexs.size() > 0) {
                Integer sex = sexs.get(0);
                user.setSex(sex);
            }
            String birthday = requestBean.getRequestParamString("birthday");
            if (birthday != null) {
                birthday = birthday.substring(0, 10);
            }
            String mobilePhone = requestBean.getRequestParamString("phoneNum");

            user.setUserName(userName);
            user.setPassword(password);
            user.setAnswer(answer);
            user.setBirthday(birthday);
            user.setMobilePhone(mobilePhone);

            int num = registerDao.register(user);

            if (num > 0) {
                responseBean.setResult(ResultConstant.SUCCESS);
            } else {
                responseBean.setResult(ResultConstant.ERROR);
            }
        }
        return responseBean;
    }

    /**
     * 微信小程序入口用户信息登记
     *
     * @param requestBean
     * @return
     */
    public ResponseBean wxregister(RequestBean requestBean) {

        ResponseBean responseBean = requestBean.getResponseBean();
        InfsUsers user = new InfsUsers();

        String openId = requestBean.getRequestParamString("openid");
        try {
            String nickName = requestBean.getRequestParamString("nickName");
            String avatarUrl = requestBean.getRequestParamString("avatarUrl");
            String gender = requestBean.getRequestParamString("gender");

            user.setNickName(nickName);
            user.setUserPicture(avatarUrl);
            user.setSex(Integer.parseInt(gender));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr = sdf.format(new Date());
            if (openId == null || "".equals(openId)) {
                throw new Exception(ResultConstant.ERROR_OPENID_NULL);
            }
            //根据用户名判断是否已经存在用户
            Map<String, Object> userMap = registerDao.findUserByOpenid(openId);
            if (userMap != null) {
                Integer userId = (Integer) userMap.get("user_id");
                user.setUserId(userId);
                Integer userType = getUserType(userId);
                userMap.put("userType", userType);
                user.setLastLogin(dateStr);
                user.setLastModTime(dateStr);
                registerDao.updateInfsUser(user);
            } else {
                //微信小程序获取不到一下数据，先填充掉
                user.setUserName(openId);
                user.setPassword(Constant.EMPTY_FILLED);
                user.setAnswer(Constant.EMPTY_FILLED);
                user.setQuestion(Constant.EMPTY_FILLED);
                user.setRegTime(sdf.format(new Date()));
                //插入用户表INFS_USER
                registerDao.register(user);
                Integer userId = user.getUserId();
                Integer userType = getUserType(userId);

                //插入用户扩展表intu_wx_user_info
                userMap = new HashMap<>(16);
                userMap.put("userId", userId);
                userMap.put("userType", userType);
                userMap.put("openid", openId);
                registerDao.insertIntuWxUserInfo(userMap);
                userMap.put("user_id", user.getUserId());
            }
            loginTokenService.saveLoginToken(requestBean.getToken(), userMap, true);
            responseBean.addResultItem("userId", MapUtils.getInteger(userMap, "user_id"));
            responseBean.addResultItem("userType", MapUtils.getInteger(userMap, "userType"));
            responseBean.setResult(ResultConstant.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            responseBean.setMessage(e.getMessage().substring(0, 100));
            Map<String, Object> userMap = registerDao.findUserByOpenid(openId);
            if (userMap != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = sdf.format(new Date());
                Integer userId = (Integer) userMap.get("user_id");
                user.setUserId(userId);
                Integer userType = getUserType(userId);
                userMap.put("userType", userType);
                user.setLastLogin(dateStr);
                user.setLastModTime(dateStr);
                registerDao.updateInfsUser(user);
                responseBean.addResultItem("userId", MapUtils.getInteger(userMap, "user_id"));
                responseBean.addResultItem("userType", MapUtils.getInteger(userMap, "userType"));
                responseBean.setResult(ResultConstant.SUCCESS);
            }
        }
        return responseBean;
    }

    /**
     * 获取用户类型
     * @param userId 用户id
     * @return 用户类型
     */
    private Integer getUserType(Integer userId){
        List<Integer> typeList = registerDao.getUserType(userId);
        Integer userType = 0;
        if (typeList.size() > 0) {
            userType = typeList.get(0);
        }
        return userType;
    }
}
